package com.agileboot.domain.performance.submission;

import cn.hutool.core.util.StrUtil;
import com.agileboot.common.core.page.PageDTO;
import com.agileboot.common.utils.jackson.JacksonUtil;
import com.agileboot.domain.performance.submission.command.AddSubmissionCommand;
import com.agileboot.domain.performance.submission.command.BatchReviewSubmissionCommand;
import com.agileboot.domain.performance.submission.command.UpdateSubmissionCommand;
import com.agileboot.domain.performance.submission.db.SubmissionEntity;
import com.agileboot.domain.performance.submission.db.SubmissionService;
import com.agileboot.domain.performance.score.UserScoreRecordApplicationService;
import com.agileboot.domain.performance.score.db.UserScoreRecordEntity;
import com.agileboot.domain.performance.score.db.UserScoreRecordService;
import com.agileboot.domain.performance.submission.dto.SubmissionDTO;
import com.agileboot.domain.performance.submission.dto.SubmissionStatisticsDTO;
import com.agileboot.domain.performance.submission.model.SubmissionModel;
import com.agileboot.domain.performance.submission.model.SubmissionModelFactory;
import com.agileboot.domain.performance.submission.query.SubmissionQuery;
import com.agileboot.domain.system.user.db.SysUserEntity;
import com.agileboot.domain.system.user.db.SysUserService;
import com.agileboot.infrastructure.cache.RedisUtil;
import com.agileboot.infrastructure.user.web.SystemLoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 绩效上报项应用服务类
 */
@Service
@RequiredArgsConstructor
public class SubmissionApplicationService {

    private final SubmissionModelFactory submissionModelFactory;

    private final SubmissionService submissionService;

    private final SysUserService sysUserService;

    private final UserScoreRecordApplicationService userScoreRecordApplicationService;

    private final UserScoreRecordService userScoreRecordService;

    private final RedisUtil redisUtil;

    /**
     * 缓存键前缀
     */
    private static final String CACHE_KEY_PREFIX_USER_STATISTICS = "performance:user_statistics:";
    private static final int CACHE_EXPIRATION_HOURS = 24; // 缓存过期时间：24小时

    public PageDTO<SubmissionDTO> getSubmissionList(SubmissionQuery query) {
        Page<SubmissionEntity> page = submissionService.page(query.toPage(), query.toQueryWrapper());
        List<SubmissionDTO> records = convertEntitiesToDTOs(page.getRecords());
        return new PageDTO<>(records, page.getTotal());
    }

    public SubmissionDTO getSubmissionInfo(Long id) {
        SubmissionEntity entity = submissionService.getById(id);
        if (entity == null) {
            return null;
        }
        return convertEntitiesToDTOs(List.of(entity)).get(0);
    }

    public void addSubmission(AddSubmissionCommand addCommand) {
        // 检查是否为多项目分配
        boolean isMultiProject = checkIsMultiProject(addCommand.getDetailsJson());
        
        if (isMultiProject && StrUtil.isNotBlank(addCommand.getAllocationDetails())) {
            // 多项目分配：items中第一个是负责人项目，后续是子项目
            List<AllocationItem> items = parseAllocationItems(addCommand.getAllocationDetails());
            if (items != null && !items.isEmpty()) {
                Long leaderId = null;
                
                // 遍历items，第一个是负责人项目，后续是子项目
                for (int i = 0; i < items.size(); i++) {
                    AllocationItem item = items.get(i);
                    SubmissionModel submissionModel = submissionModelFactory.create();
                    submissionModel.loadFromAddCommand(addCommand);
                    
                    // 设置owner和ownerScore
                    submissionModel.setOwner(item.getUserId());
                    submissionModel.setOwnerScore(item.getScore());
                    
                    if (i == 0) {
                        // 第一个是负责人项目，fatherId为null
                        submissionModel.setFatherId(null);
                        submissionModel.checkTitleUnique();
                        submissionModel.insert();
                        leaderId = submissionModel.getId();
                    } else {
                        // 后续是子项目，fatherId为负责人项目的ID
                        submissionModel.setFatherId(leaderId);
                        submissionModel.checkTitleUnique();
                        submissionModel.insert();
                    }
                }
                
                // 清除相关缓存
                for (AllocationItem item : items) {
                    if (item.getUserId() != null) {
                        clearUserStatisticsCache(item.getUserId().longValue());
                    }
                }
                return;
            }
        }
        
        // 单项目：保持原样执行
        SubmissionModel submissionModel = submissionModelFactory.create();
        submissionModel.loadFromAddCommand(addCommand);
        submissionModel.setFatherId(null); // 单项目的fatherId为null

        submissionModel.checkTitleUnique();

        submissionModel.insert();
        
        // 清除相关缓存
        if (submissionModel.getOwner() != null) {
            clearUserStatisticsCache(submissionModel.getOwner().longValue());
        }
    }
    
    /**
     * 检查detailsJson中的isMultiProject属性
     */
    private boolean checkIsMultiProject(String detailsJson) {
        if (StrUtil.isBlank(detailsJson)) {
            return false;
        }
        try {
            JsonNode jsonNode = JacksonUtil.getObjectMapper().readTree(detailsJson);
            JsonNode isMultiProjectNode = jsonNode.get("isMultiProject");
            if (isMultiProjectNode != null && isMultiProjectNode.isBoolean()) {
                return isMultiProjectNode.asBoolean();
            }
        } catch (Exception e) {
            // 解析失败，返回false
        }
        return false;
    }
    
    /**
     * 解析allocationDetails中的items数组
     */
    private List<AllocationItem> parseAllocationItems(String allocationDetails) {
        if (StrUtil.isBlank(allocationDetails)) {
            return new ArrayList<>();
        }
        try {
            JsonNode jsonNode = JacksonUtil.getObjectMapper().readTree(allocationDetails);
            JsonNode itemsNode = jsonNode.get("items");
            if (itemsNode != null && itemsNode.isArray()) {
                List<AllocationItem> items = new ArrayList<>();
                for (JsonNode itemNode : itemsNode) {
                    AllocationItem item = new AllocationItem();
                    if (itemNode.has("userId")) {
                        item.setUserId(itemNode.get("userId").asInt());
                    }
                    if (itemNode.has("score")) {
                        item.setScore(itemNode.get("score").asDouble());
                    }
                    items.add(item);
                }
                return items;
            }
        } catch (Exception e) {
            // 解析失败，返回空列表
        }
        return new ArrayList<>();
    }
    
    /**
     * 分配项内部类
     */
    @Data
    private static class AllocationItem {
        private Integer userId;
        private Double score;
    }
    
    /**
     * 获取子项目列表
     * @param fatherId 父项目ID
     * @return 子项目列表
     */
    private List<SubmissionEntity> getChildSubmissions(Long fatherId) {
        if (fatherId == null) {
            return Collections.emptyList();
        }
        QueryWrapper<SubmissionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("father_id", fatherId);
        return submissionService.list(queryWrapper);
    }
    
    /**
     * 删除子项目
     * @param fatherId 父项目ID
     */
    private void deleteChildSubmissions(Long fatherId) {
        if (fatherId == null) {
            return;
        }
        QueryWrapper<SubmissionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("father_id", fatherId);
        submissionService.remove(queryWrapper);
    }

    public void updateSubmission(UpdateSubmissionCommand updateCommand) {
        SubmissionModel submissionModel = submissionModelFactory.loadById(updateCommand.getId());
        
        // 保存旧的owner，用于清除缓存
        Integer oldOwner = submissionModel.getOwner();
        
        // 检查是否为多项目分配
        boolean isMultiProject = checkIsMultiProject(updateCommand.getDetailsJson());
        
        // 先加载更新命令，这会复制command中的属性到model
        submissionModel.loadFromUpdateCommand(updateCommand);
        
        // 收集所有相关的owner ID（包括旧的owner和新的owner，用于清除缓存）
        Set<Long> ownerIds = new HashSet<>();
        if (oldOwner != null) {
            ownerIds.add(oldOwner.longValue());
        }
        
        // 如果是负责人项目（fatherId为null），需要处理子项目
        if (submissionModel.getFatherId() == null) {
            // 先删除所有子项目（需要先获取旧子项目的owner）
            List<SubmissionEntity> oldChildSubmissions = getChildSubmissions(updateCommand.getId());
            for (SubmissionEntity oldChild : oldChildSubmissions) {
                if (oldChild.getOwner() != null) {
                    ownerIds.add(oldChild.getOwner().longValue());
                }
            }
            deleteChildSubmissions(updateCommand.getId());
            
            // 如果是多人参与的项目，根据allocation_details更新主项目和子项目
            if (isMultiProject && StrUtil.isNotBlank(updateCommand.getAllocationDetails())) {
                List<AllocationItem> items = parseAllocationItems(updateCommand.getAllocationDetails());
                if (items != null && !items.isEmpty()) {
                    // items中第一个是负责人项目，用于更新主项目的owner和ownerScore
                    AllocationItem leaderItem = items.get(0);
                    if (leaderItem != null) {
                        submissionModel.setOwner(leaderItem.getUserId());
                        submissionModel.setOwnerScore(leaderItem.getScore());
                        if (submissionModel.getOwner() != null) {
                            ownerIds.add(submissionModel.getOwner().longValue());
                        }
                    }
                    
                    // 从第二个开始才是子项目，重新创建子项目
                    for (int i = 1; i < items.size(); i++) {
                        AllocationItem item = items.get(i);
                        SubmissionModel childModel = submissionModelFactory.create();
                        childModel.loadFromAddCommand(updateCommand);
                        
                        // 设置owner和ownerScore
                        childModel.setOwner(item.getUserId());
                        childModel.setOwnerScore(item.getScore());
                        if (childModel.getOwner() != null) {
                            ownerIds.add(childModel.getOwner().longValue());
                        }
                        // 设置fatherId为负责人项目的ID
                        childModel.setFatherId(updateCommand.getId());
                        // creatorId保持为当前用户ID（已在loadFromAddCommand中设置）
                        
                        childModel.checkTitleUnique();
                        childModel.insert();
                    }
                }
            } else {
                // 非多项目分配，添加新的owner
                if (submissionModel.getOwner() != null) {
                    ownerIds.add(submissionModel.getOwner().longValue());
                }
            }
        } else {
            // 子项目，添加新的owner
            if (submissionModel.getOwner() != null) {
                ownerIds.add(submissionModel.getOwner().longValue());
            }
        }
        
        submissionModel.checkTitleUnique();
        submissionModel.updateById();
        
        // 清除相关缓存
        for (Long ownerId : ownerIds) {
            clearUserStatisticsCache(ownerId);
        }
    }

    public void deleteSubmission(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        
        // 查询所有需要删除的实体
        List<SubmissionEntity> entities = submissionService.listByIds(ids);
        if (entities.isEmpty()) {
            return;
        }
        
        // 收集所有需要删除的ID（包括子项目和父项目）
        Set<Long> allDeleteIds = entities.stream()
                .map(SubmissionEntity::getId)
                .collect(Collectors.toSet());
        
        // 处理每个实体，收集相关的子项目或父项目
        for (SubmissionEntity entity : entities) {
            if (entity.getFatherId() == null) {
                // 这是负责人项目，查找所有子项目
                List<SubmissionEntity> childEntities = getChildSubmissions(entity.getId());
                for (SubmissionEntity child : childEntities) {
                    allDeleteIds.add(child.getId());
                }
            } else {
                // 这是子项目，需要包含父项目和其他子项目
                Long fatherId = entity.getFatherId();
                allDeleteIds.add(fatherId);
                List<SubmissionEntity> childEntities = getChildSubmissions(fatherId);
                for (SubmissionEntity child : childEntities) {
                    allDeleteIds.add(child.getId());
                }
            }
        }
        
        // 查询所有需要删除的实体（包括子项目和父项目），用于获取owner
        List<SubmissionEntity> allEntities = submissionService.listByIds(new ArrayList<>(allDeleteIds));
        
        // 收集所有owner
        Set<Long> ownerIds = allEntities.stream()
                .filter(entity -> entity.getOwner() != null)
                .map(entity -> entity.getOwner().longValue())
                .collect(Collectors.toSet());
        
        // 检查删除权限
        for (Long id : ids) {
            SubmissionModel submissionModel = submissionModelFactory.loadById(id);
            submissionModel.checkCanBeDeleted();
        }
        
        // 执行删除（删除所有相关的项目，包括子项目）
        submissionService.removeBatchByIds(new ArrayList<>(allDeleteIds));
        
        // 为每个owner提交统计任务并清除缓存
        for (Long ownerId : ownerIds) {
            userScoreRecordApplicationService.submitCalculateUserScoreTask(ownerId);
            clearUserStatisticsCache(ownerId);
        }
    }

    /**
     * 批量提交绩效上报项
     * @param ids 绩效上报项ID列表
     */
    public void batchSubmit(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        // 查询所有需要更新的实体
        List<SubmissionEntity> entities = submissionService.listByIds(ids);
        if (entities.isEmpty()) {
            return;
        }
        
        // 收集所有需要提交的ID（包括子项目和父项目）
        Set<Long> allSubmitIds = entities.stream()
                .map(SubmissionEntity::getId)
                .collect(Collectors.toSet());
        
        // 处理每个实体
        for (SubmissionEntity entity : entities) {
            if (entity.getFatherId() == null) {
                // 这是负责人项目，查找所有子项目
                List<SubmissionEntity> childEntities = getChildSubmissions(entity.getId());
                for (SubmissionEntity child : childEntities) {
                    allSubmitIds.add(child.getId());
                }
            } else {
                // 这是子项目，需要包含父项目和其他子项目
                Long fatherId = entity.getFatherId();
                allSubmitIds.add(fatherId);
                List<SubmissionEntity> childEntities = getChildSubmissions(fatherId);
                for (SubmissionEntity child : childEntities) {
                    allSubmitIds.add(child.getId());
                }
            }
        }
        
        // 查询所有需要更新的实体（包括子项目和父项目）
        List<SubmissionEntity> allEntities = submissionService.listByIds(new ArrayList<>(allSubmitIds));
        
        // 批量更新状态和审核层级
        for (SubmissionEntity entity : allEntities) {
            entity.setStatus("PENDING_AUDIT");
            entity.setCurrentAuditLevel(1);
        }
        // 批量更新到数据库
        submissionService.updateBatchById(allEntities);
        
        // 从实体中获取owner，去重后调用统计接口
        Set<Long> ownerIds = allEntities.stream()
                .filter(entity -> entity.getOwner() != null)
                .map(entity -> entity.getOwner().longValue())
                .collect(Collectors.toSet());
        
        // 为每个owner提交统计任务并清除缓存
        for (Long ownerId : ownerIds) {
            userScoreRecordApplicationService.submitCalculateUserScoreTask(ownerId);
            clearUserStatisticsCache(ownerId);
        }
    }

    /**
     * 批量审核绩效上报项
     * @param loginUser 当前登录用户
     * @param command 审核命令
     */
    public void batchReview(SystemLoginUser loginUser, BatchReviewSubmissionCommand command) {
        if (command == null || command.getIdList() == null || command.getIdList().isEmpty()) {
            return;
        }

        List<SubmissionEntity> entities = submissionService.listByIds(command.getIdList());
        if (entities.isEmpty()) {
            return;
        }

        // 扩展到多人项目的父子关联：与 batchSubmit 逻辑一致
        Set<Long> allReviewIds = entities.stream()
                .map(SubmissionEntity::getId)
                .collect(Collectors.toSet());
        for (SubmissionEntity entity : entities) {
            if (entity.getFatherId() == null) {
                // 负责人项目：包含所有子项目
                List<SubmissionEntity> childEntities = getChildSubmissions(entity.getId());
                for (SubmissionEntity child : childEntities) {
                    allReviewIds.add(child.getId());
                }
            } else {
                // 子项目：包含父项目及其所有子项目
                Long fatherId = entity.getFatherId();
                allReviewIds.add(fatherId);
                List<SubmissionEntity> childEntities = getChildSubmissions(fatherId);
                for (SubmissionEntity child : childEntities) {
                    allReviewIds.add(child.getId());
                }
            }
        }
        // 查询所有需要审核的实体（包括子项目和父项目）
        List<SubmissionEntity> allEntities = submissionService.listByIds(new ArrayList<>(allReviewIds));

        Long reviewerId = loginUser != null ? loginUser.getUserId() : null;
        String reviewerName = null;
        if (reviewerId != null) {
            SysUserEntity reviewer = sysUserService.getById(reviewerId);
            if (reviewer != null) {
                reviewerName = reviewer.getNickname();
            }
        }
        if (StrUtil.isBlank(reviewerName) && loginUser != null) {
            reviewerName = loginUser.getUsername();
        }

        boolean approved = Boolean.TRUE.equals(command.getApproved());
        Set<Long> ownerIdsForScore = new HashSet<>();
        for (SubmissionEntity entity : allEntities) {
            if (entity == null) {
                continue;
            }
            Integer originalLevelObj = entity.getCurrentAuditLevel();
            int originalLevel = originalLevelObj == null ? 0 : originalLevelObj;
            if (originalLevel >= 4) {
                continue;
            }

            Date reviewTime = new Date();

            if (!approved) {
                entity.setStatus("REJECTED");
                entity.setRejectionReason(command.getReason());
                entity.setCurrentAuditLevel(0);
            } else {
                entity.setRejectionReason(null);
                entity.setCurrentAuditLevel(originalLevel + 1);
                if (originalLevel == 3) {
                    entity.setStatus("APPROVED");
                    if (entity.getOwner() != null) {
                        ownerIdsForScore.add(entity.getOwner().longValue());
                    }
                }
            }

            if (originalLevel == 1) {
                entity.setFirstReviewerName(reviewerName);
                entity.setFirstReviewTime(reviewTime);
            } else if (originalLevel == 2) {
                entity.setSecondReviewerName(reviewerName);
                entity.setSecondReviewTime(reviewTime);
            } else if (originalLevel == 3) {
                entity.setThirdReviewerName(reviewerName);
                entity.setThirdReviewTime(reviewTime);
            }
        }

        submissionService.updateBatchById(allEntities);

        for (Long ownerId : ownerIdsForScore) {
            userScoreRecordApplicationService.submitCalculateUserScoreTask(ownerId);
        }
        
        // 清除相关缓存
        Set<Long> allOwnerIds = allEntities.stream()
                .filter(entity -> entity.getOwner() != null)
                .map(entity -> entity.getOwner().longValue())
                .collect(Collectors.toSet());
        for (Long ownerId : allOwnerIds) {
            clearUserStatisticsCache(ownerId);
        }
    }

    /**
     * 导出所有绩效上报项
     * 使用分批查询避免大数据量查询导致的内存问题和性能问题
     */
    public List<SubmissionDTO> getSubmissionListAll(SubmissionQuery query) {
        // 分批查询大小，每次查询1000条
        final int batchSize = 1000;
        List<SubmissionDTO> allDTOs = new ArrayList<>();
        
        // 获取查询条件
        QueryWrapper<SubmissionEntity> queryWrapper = query.toQueryWrapper();
        
        // 分批查询
        int currentPage = 1;
        boolean hasMore = true;
        
        while (hasMore) {
            // 创建分页对象
            Page<SubmissionEntity> page = new Page<>(currentPage, batchSize);
            
            // 执行分页查询
            Page<SubmissionEntity> pageResult = submissionService.page(page, queryWrapper);
            List<SubmissionEntity> batch = pageResult.getRecords();
            
            if (batch.isEmpty()) {
                hasMore = false;
            } else {
                // 分批转换为DTO
                List<SubmissionDTO> batchDTOs = convertEntitiesToDTOs(batch);
                allDTOs.addAll(batchDTOs);
                
                // 检查是否还有更多数据：如果当前批次数量小于批次大小，说明已经是最后一批
                hasMore = batch.size() >= batchSize;
                currentPage++;
            }
        }
        
        return allDTOs;
    }

    /**
     * 将实体列表转换为DTO列表，并填充用户名称信息
     * @param entities SubmissionEntity列表
     * @return SubmissionDTO列表
     */
    private List<SubmissionDTO> convertEntitiesToDTOs(List<SubmissionEntity> entities) {
        if (entities.isEmpty()) {
            return Collections.emptyList();
        }

        // 收集所有需要查询的用户ID（creatorId 和 owner）
        Set<Long> userIds = entities.stream()
                .filter(entity -> entity != null)
                .flatMap(entity -> {
                    List<Long> ids = new ArrayList<>();
                    if (entity.getCreatorId() != null) {
                        ids.add(entity.getCreatorId());
                    }
                    if (entity.getOwner() != null) {
                        ids.add(entity.getOwner().longValue());
                    }
                    return ids.stream();
                })
                .collect(Collectors.toSet());

        // 批量获取用户信息
        Map<Long, SysUserEntity> userMap;
        if (!userIds.isEmpty()) {
            List<SysUserEntity> userEntities = sysUserService.getByUserIds(new ArrayList<>(userIds));
            userMap = userEntities.stream()
                    .filter(user -> user != null)
                    .collect(Collectors.toMap(
                            SysUserEntity::getUserId,
                            user -> user,
                            (existing, replacement) -> existing
                    ));
        } else {
            userMap = Collections.emptyMap();
        }

        // 转换为DTO并填充用户名称
        final Map<Long, SysUserEntity> finalUserMap = userMap;
        return entities.stream().map(entity -> {
            SubmissionDTO dto = new SubmissionDTO(entity);

            // 设置创建者姓名
            if (entity.getCreatorId() != null) {
                SysUserEntity creator = finalUserMap.get(entity.getCreatorId());
                if (creator != null) {
                    dto.setCreatorName(creator.getNickname());
                }
            }

            // 设置所有者姓名
            if (entity.getOwner() != null) {
                SysUserEntity owner = finalUserMap.get(entity.getOwner().longValue());
                if (owner != null) {
                    dto.setOwnerName(owner.getNickname());
                }
            }

            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 获取本人申报的项目数量信息和分数信息（带缓存）
     * @param userId 用户ID
     * @return 统计信息
     */
    public SubmissionStatisticsDTO getUserSubmissionStatistics(Long userId) {
        if (userId == null) {
            return null;
        }

        String cacheKey = CACHE_KEY_PREFIX_USER_STATISTICS + userId;
        SubmissionStatisticsDTO cached = redisUtil.getCacheObject(cacheKey);
        if (cached != null) {
            return cached;
        }

        // 查询submissions表：deleted=0且owner为当前用户id
        QueryWrapper<SubmissionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0)
                .eq("owner", userId);
        List<SubmissionEntity> submissions = submissionService.list(queryWrapper);

        // 定义五种主类别
        String[] mainCategories = {"教研工作量", "科研工作量", "育人工作量", "服务工作量", "其他工作量"};
        String[] statuses = {"DRAFT", "PENDING_AUDIT", "REJECTED", "APPROVED"};

        // 初始化统计结果
        Map<String, Map<String, Long>> projectCountByCategoryAndStatus = new HashMap<>();
        for (String category : mainCategories) {
            Map<String, Long> statusCount = new HashMap<>();
            for (String status : statuses) {
                statusCount.put(status, 0L);
            }
            projectCountByCategoryAndStatus.put(category, statusCount);
        }

        // 统计项目数量
        for (SubmissionEntity submission : submissions) {
            String mainCategory = submission.getMainCategory();
            String status = submission.getStatus();
            if (mainCategory != null && projectCountByCategoryAndStatus.containsKey(mainCategory)) {
                Map<String, Long> statusCount = projectCountByCategoryAndStatus.get(mainCategory);
                if (status != null && statusCount.containsKey(status)) {
                    statusCount.put(status, statusCount.get(status) + 1);
                }
            }
        }

        // 查询分数信息
        QueryWrapper<UserScoreRecordEntity> scoreQuery = new QueryWrapper<>();
        scoreQuery.eq("user_id", userId);
        UserScoreRecordEntity scoreRecord = userScoreRecordService.getOne(scoreQuery);

        SubmissionStatisticsDTO.ScoreInfoDTO scoreInfo = new SubmissionStatisticsDTO.ScoreInfoDTO();
        if (scoreRecord != null) {
            scoreInfo.setResearchWorkload(scoreRecord.getResearchWorkload() != null ? scoreRecord.getResearchWorkload() : BigDecimal.ZERO);
            scoreInfo.setTeachingWorkload(scoreRecord.getTeachingWorkload() != null ? scoreRecord.getTeachingWorkload() : BigDecimal.ZERO);
            scoreInfo.setEducationWorkload(scoreRecord.getEducationWorkload() != null ? scoreRecord.getEducationWorkload() : BigDecimal.ZERO);
            scoreInfo.setServiceWorkload(scoreRecord.getServiceWorkload() != null ? scoreRecord.getServiceWorkload() : BigDecimal.ZERO);
            scoreInfo.setOtherWorkload(scoreRecord.getOtherWorkload() != null ? scoreRecord.getOtherWorkload() : BigDecimal.ZERO);
            scoreInfo.setGeneralCourseScore(scoreRecord.getGeneralCourseScore() != null ? scoreRecord.getGeneralCourseScore() : BigDecimal.ZERO);
            scoreInfo.setMajorCourseScore(scoreRecord.getMajorCourseScore() != null ? scoreRecord.getMajorCourseScore() : BigDecimal.ZERO);
            scoreInfo.setLabCourseScore(scoreRecord.getLabCourseScore() != null ? scoreRecord.getLabCourseScore() : BigDecimal.ZERO);
            scoreInfo.setPendingScore(scoreRecord.getPendingScore() != null ? scoreRecord.getPendingScore() : BigDecimal.ZERO);
            scoreInfo.setApprovedTotalScore(scoreRecord.getApprovedTotalScore() != null ? scoreRecord.getApprovedTotalScore() : BigDecimal.ZERO);
        } else {
            scoreInfo.setResearchWorkload(BigDecimal.ZERO);
            scoreInfo.setTeachingWorkload(BigDecimal.ZERO);
            scoreInfo.setEducationWorkload(BigDecimal.ZERO);
            scoreInfo.setServiceWorkload(BigDecimal.ZERO);
            scoreInfo.setOtherWorkload(BigDecimal.ZERO);
            scoreInfo.setGeneralCourseScore(BigDecimal.ZERO);
            scoreInfo.setMajorCourseScore(BigDecimal.ZERO);
            scoreInfo.setLabCourseScore(BigDecimal.ZERO);
            scoreInfo.setPendingScore(BigDecimal.ZERO);
            scoreInfo.setApprovedTotalScore(BigDecimal.ZERO);
        }

        SubmissionStatisticsDTO result = new SubmissionStatisticsDTO(projectCountByCategoryAndStatus, scoreInfo);

        // 缓存结果
        redisUtil.setCacheObject(cacheKey, result, CACHE_EXPIRATION_HOURS, TimeUnit.HOURS);

        return result;
    }

    /**
     * 清除用户统计缓存
     * @param userId 用户ID
     */
    private void clearUserStatisticsCache(Long userId) {
        if (userId != null) {
            String cacheKey = CACHE_KEY_PREFIX_USER_STATISTICS + userId;
            redisUtil.deleteObject(cacheKey);
        }
    }
}
